import React, { useState } from 'react';
import styles from './index.less';
import { Modal, Upload, Button, Spin } from 'antd';
import { getDvaApp } from 'umi';

// import appLogoDefault from '@/assets/img/appLogo.png';
import appLogoDefault from '@/layouts/appLogo.png';
import { TRAlert, TRMessage } from '@/components';
import TRNotification from '@/utils/notification';
import { saveLogo, setDefultLogo } from '@/services/power';
import { HttpCode } from '@/utils/contacts';

const EditAppLogo = ({ appLogo, onPress }) => {
  const [loading, setLoading] = useState(false);
  const [restore, setRestore] = useState(false); // 是否还原LOGO
  const [file, setFile] = useState('');
  const [logo, setLogo] = useState(appLogo);

  const handleCancel = () => {
    onPress({ index: 0 });
  };

  const updateLogo = () => {
    const { dispatch } = getDvaApp()._store;
    dispatch?.({ type: 'user/setAppLogo' });
    onPress({ index: 0 });
  };

  // 还原logo
  const handleReset = () => {
    setRestore(true);
    setFile('');
    setLogo(appLogoDefault);
  };

  const beforeUpload = (file) => {
    setRestore(false);
    setFile(file);
    setLogo(URL.createObjectURL(new Blob([file])));
  };

  const handleSubmit = async () => {
    if (file) {
      setLoading(true);
      const formData = new window.FormData();
      formData.append('file', file);
      const res = await saveLogo(formData);
      setLoading(false);
      if (res?.statusCode === HttpCode.SUCCESS) {
        TRMessage.success('上传成功');
        updateLogo();
      } else {
        return TRAlert.error('上传图片有误，请重新上传！');
      }
    } else {
      if (!restore) return handleCancel();
      if (restore) {
        setLoading(true);
        const res = await setDefultLogo();
        setLoading(false);
        if (res?.statusCode === HttpCode.SUCCESS) {
          TRMessage.success('还原成功');
          updateLogo();
        } else {
          return TRMessage.error(res?.message || '还原失败，稍后再试！');
        }
      }
    }
  };

  return (
    <Modal
      visible={true}
      title={false}
      onCancel={handleCancel}
      maskClosable={false}
      footer={false}
      centered={true}
      width={465}
      wrapClassName={styles.logo_modal}
    >
      <Spin spinning={loading}>
        <div className={styles.head}>
          <span>更换LOGO</span>
        </div>
        <div className={styles.main}>
          <div className={styles.title}>上传您公司/组织的LOGO</div>
          <div className={styles.logo_upload}>
            <div className={styles.logo_img}>
              <img src={logo} />
            </div>
            <Upload
              itemRender={() => {}}
              accept=".png,.jpg,.jpeg,.gif"
              maxCount="1"
              beforeUpload={beforeUpload}
            >
              <div className={`${styles.btn} ${styles.primary}`}>重新上传</div>
            </Upload>
            <div className={styles.btn} onClick={handleReset}>
              还原默认LOGO
            </div>
          </div>
          <div className={styles.logo_size}>
            <div>请按要求上传：</div>
            <div>1.尺寸建议：150px*54px；</div>
            <div>2.格式要求：透明背景图片，png、jpg、jpeg或gif</div>
          </div>
          <div className={styles.title}>示例</div>
          <div className={styles.logo_example}>
            <div className={styles.logo_example_img}>
              <img src={appLogoDefault} />
              <div>建议：LOGO图形不能使用黑色</div>
            </div>
          </div>
          <div className={styles.footer}>
            <div onClick={handleCancel}>取消</div>
            <div className={styles.primary} onClick={handleSubmit}>
              保存
            </div>
          </div>
        </div>
      </Spin>
    </Modal>
  );
};

class EditAppLogoModal extends React.Component {
  __key__ = '';
  show = (props = {}) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') {
        return;
      }
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <EditAppLogo
            {...props}
            onPress={() => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve();
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

const TREditAppLogoModal = new EditAppLogoModal();

export default TREditAppLogoModal;
